var express = require('express');
const fs = require('fs');
const path = require('path');
const uuidv1 = require('uuid/v1');
const HttpUrlUtil = require('../server/util/httpurl.util');

const config = require('../server/config/server.config.js');

var router = express.Router();

router.use(function (req, res) {
    if (req.busboy) {
        let picId = uuidv1();
        let saveTo = path.join(config.idcardpicPath, path.basename(picId));
        let httpUrl = 'http://' + config.serverUrl + '/idcardpic/' + path.basename(picId);
        req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            saveTo += HttpUrlUtil.getSuffixOfFile(filename);
            httpUrl += HttpUrlUtil.getSuffixOfFile(filename);
            file.pipe(fs.createWriteStream(saveTo));
        });
        req.busboy.on('finish', function () {
            res.send(
                {
                    status: 'success',
                    type: 'idcardpic',
                    picId: picId,
                    path: httpUrl
                }
            );
        });
        req.pipe(req.busboy);
    }
});

module.exports = router;
